package utils

import (
	"encoding/csv"
	"fmt"
	"github.com/extrame/xls"
	"github.com/tealeg/xlsx"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
)

//os.PathSeparator

const (
	CSV  string = ".csv"
	XLS  string = ".xls"
	XLSX string = ".xlsx"
)

var filePath string = ""
var fileName = ""

func FileIfExist(filename string) bool {
	_, err := os.Stat(filename)
	if nil != err {
		fmt.Println(filename, "is not exist!")
		return false
	}
	if os.IsNotExist(err) {
		return false
	}
	return true
}

func GetFileExt(filePath string) string {
	fileExt := path.Ext(filePath)
	return fileExt
}

func GetFileName(filePath string) string {
	_, file := filepath.Split(filePath)
	fileNameClear := strings.TrimSuffix(file, path.Ext(filePath))
	return fileNameClear
}

func GetNewPath(filePath string, oldFileExt string) string {
	dir, file := filepath.Split(filePath)
	fileName = strings.TrimSuffix(file, oldFileExt)
	return dir
}

func ReadCsv(file_path string) (res map[string][][]string) {
	fileName = GetFileName(file_path)
	// 打开文件
	file, err := os.Open(file_path)
	if err != nil {
		log.Println("open_err:")
		log.Println(err)
		return
	}
	defer file.Close()
	// 初始化csv-reader
	reader := csv.NewReader(file)
	// 设置返回记录中每行数据期望的字段数，-1 表示返回所有字段
	reader.FieldsPerRecord = -1
	// 允许懒引号（忘记遇到哪个问题才加的这行）
	reader.LazyQuotes = true
	// 返回csv中的所有内容
	records, read_err := reader.ReadAll()
	if read_err != nil {
		log.Println("read_err:")
		log.Println(read_err)
		return
	}
	res = make(map[string][][]string)
	res[fileName] = records
	return res
}

func ReadXlsxAllSheet(file_path string) (res map[string][][]string) {
	res = make(map[string][][]string)
	if xlFile, err := xlsx.OpenFile(file_path); err == nil {
		for _, sheet := range xlFile.Sheets {
			//第一个sheet
			log.Println(sheet.Name)
			temp := make([][]string, len(sheet.Rows))
			for k, row := range sheet.Rows {
				var data []string
				for _, cell := range row.Cells {
					data = append(data, cell.Value)
				}
				temp[k] = data
			}
			res[sheet.Name] = temp
		}
	} else {
		log.Println("open_err:")
		log.Println(err)
	}
	return res
}

func ReadXlsAllSheet(file_path string) (res map[string][][]string) {
	if xlFile, err := xls.Open(file_path, "utf-8"); err == nil {
		res = make(map[string][][]string)
		fmt.Println(xlFile.Author)
		sheetCount := xlFile.NumSheets()
		for i := 0; i < sheetCount; i++ {
			sheet := xlFile.GetSheet(i)
			if sheet.MaxRow != 0 {
				temp := make([][]string, 0, sheet.MaxRow)
				for i := 0; i < int(sheet.MaxRow); i++ {
					row := sheet.Row(i)
					data := make([]string, 0)
					if row.LastCol() > 0 {
						for j := 0; j < row.LastCol(); j++ {
							col := row.Col(j)
							if col != "" {
								data = append(data, col)
							}
						}
						if len(data) > 0 {
							temp = append(temp, data)
						}
					}
				}
				res[sheet.Name] = temp
			}
		}
	} else {
		log.Println("open_err:")
		log.Println(err)
	}
	return res
}
